#include "HashMapDy.h"
#include <iostream>


HashMap::HashMap(int HashSize)
{
    this->HashSize = HashSize;
    array = new Node*[this->HashSize];
    //指针数组初始化，把每一个指针置为空
    for(int i = 0; i < HashSize; i++)
    {
        array[i] = nullptr;
    }
}



/* 析构 */
//遍历，释放链表节点
HashMap::~HashMap()
{
    for(int i = 0; i < HashSize; i++)
    {
        Node * node = array[i];
        while(node != nullptr)
        {
            Node * temp = node->next;
            delete node;
            node = temp;
        }   //静态数组只释放指针就ok了
    }
    delete []array;
}

/* 插入 */
void HashMap::Insert(const std::string &key, ElementType value)
{
    Node * node = new Node(key, value); //！
    int index = Hash(key);
    // std::cout<<key<<" "<<index<<std::endl;
    if(array[index] == nullptr)
        array[index] = node;
    else
    {
        //链表头插
        node->next = array[index];
        array[index] = node;
    }

}
/* 查找 */
ElementType *HashMap::Get(const std::string &key)
{
    Node * node = array[Hash(key)]; //直接找到key对应的值
    if(node == nullptr)         //如果对应节点为空
        return nullptr;         //则返回空
    while(node != nullptr)      //如果节点不为空
    {
        if(node->key == key)    //节点的键与输入的键相等
            return &node->data; //则输出节点 //取地址是因为ElementType*,返回值是指针
        node = node->next;//否则继续遍历节点
    }
    return nullptr;
}

ElementType & HashMap::operator[](const std::string &key)
{
    ElementType*data = Get(key);
    if(data)
        return *data;    //data为指针
    else
    {
        //创建
        Insert(key,"");  //value未定，先给0
        return *Get(key);
    }
}

void HashMap::show()
{
    for(int i = 0; i < HashSize; i++)
    {
        Node * node = array[i];
        while(node != nullptr)
        {
            std::cout<<" key:"<<node->key<<"| hash:"<<Hash(node->key)<<"| value:"<<node->data<<std::endl;
            node = node->next;
        }
    }
}

void HashMap::showByKey()   //!
{
    for(int i = 0; i < HashSize; i++)
    {
        Node * node = array[i];
        if(node == nullptr)
            continue;
        while(node != nullptr)
        {
            std::cout<<node->data<<" ";
            node = node->next;
        }
        std::cout<<std::endl;
    }
}

/* Hash函数 */
int HashMap::Hash(const std::string &key)
{
    //把每一个字母的Ascll值加起来，把和乘以一个素数
    int hash = 0;
    for(int i = 0; i < key.size();i++)
    {
        hash = (hash * 31 + key[i]) % HashSize; //取余，使值落在哈希size里面
    }
    return hash;
}

void HashMap::Remove(const std::string &key)
{
}
